/**
 * 用户认证状态管理
 */
import { ref, computed } from 'vue'

export interface User {
  id: string
  name: string
  email: string
  avatar?: string
  role?: string
  createdAt?: string
  updatedAt?: string
}

// 全局用户状态
const currentUser = ref<User | null>(null)
const isLoading = ref(false)

export function useAuth() {
  // 计算属性
  const isLoggedIn = computed(() => !!currentUser.value)
  const userName = computed(() => currentUser.value?.name || '')
  const userEmail = computed(() => currentUser.value?.email || '')
  const userAvatar = computed(() => currentUser.value?.avatar)
  const userRole = computed(() => currentUser.value?.role || 'user')

  /**
   * 模拟登录
   */
  const login = async (email: string, password: string): Promise<void> => {
    isLoading.value = true

    try {
      // 模拟API调用延迟
      await new Promise((resolve) => setTimeout(resolve, 1000))

      // 模拟登录成功
      const mockUser: User = {
        id: '1',
        name: '张三',
        email: email,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${email}`,
        role: 'admin',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      }

      currentUser.value = mockUser

      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify(mockUser))
      localStorage.setItem('token', 'mock-jwt-token')

      console.log('登录成功:', mockUser)
    } catch (error) {
      console.error('登录失败:', error)
      throw new Error('登录失败，请检查用户名和密码')
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 快速登录（演示用）
   */
  const quickLogin = async (): Promise<void> => {
    isLoading.value = true

    try {
      await new Promise((resolve) => setTimeout(resolve, 500))

      const mockUser: User = {
        id: '1',
        name: '博客作者',
        email: 'author@example.com',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=author',
        role: 'admin',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      }

      currentUser.value = mockUser
      localStorage.setItem('user', JSON.stringify(mockUser))
      localStorage.setItem('token', 'mock-jwt-token')

      console.log('快速登录成功:', mockUser)
    } catch (error) {
      console.error('快速登录失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 登出
   */
  const logout = async (): Promise<void> => {
    isLoading.value = true

    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 300))

      currentUser.value = null

      // 清除本地存储
      localStorage.removeItem('user')
      localStorage.removeItem('token')

      console.log('登出成功')
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 初始化用户状态（从本地存储恢复）
   */
  const initAuth = (): void => {
    try {
      const savedUser = localStorage.getItem('user')
      const savedToken = localStorage.getItem('token')

      if (savedUser && savedToken) {
        currentUser.value = JSON.parse(savedUser)
        console.log('用户状态已恢复:', currentUser.value)
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
      // 清除损坏的数据
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    }
  }

  /**
   * 更新用户信息
   */
  const updateProfile = async (updates: Partial<User>): Promise<void> => {
    if (!currentUser.value) {
      throw new Error('用户未登录')
    }

    isLoading.value = true

    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 800))

      const updatedUser = {
        ...currentUser.value,
        ...updates,
        updatedAt: new Date().toISOString(),
      }

      currentUser.value = updatedUser
      localStorage.setItem('user', JSON.stringify(updatedUser))

      console.log('用户信息更新成功:', updatedUser)
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 检查权限
   */
  const hasPermission = (permission: string): boolean => {
    if (!currentUser.value) return false

    // 简单的权限检查逻辑
    const userRole = currentUser.value.role || 'user'

    const permissions: Record<string, string[]> = {
      admin: ['read', 'write', 'delete', 'manage'],
      editor: ['read', 'write'],
      user: ['read'],
    }

    return permissions[userRole]?.includes(permission) || false
  }

  return {
    // 状态
    currentUser: computed(() => currentUser.value),
    isLoading: computed(() => isLoading.value),
    isLoggedIn,
    userName,
    userEmail,
    userAvatar,
    userRole,

    // 方法
    login,
    quickLogin,
    logout,
    initAuth,
    updateProfile,
    hasPermission,
  }
}
